package com.snail.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.snail.exception.BizException;
import com.snail.mapper.SysTagMapper;
import com.snail.model.pojo.user.SysTag;
import com.snail.model.pojo.user.SysUserTag;
import com.snail.model.vo.user.LoginUser;
import com.snail.result.Result;
import com.snail.result.ResultCode;
import com.snail.service.SysTagService;
import com.snail.service.SysUserTagService;
import com.snail.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 标签服务实现类
 */
@Service
public class SysTagServiceImpl extends ServiceImpl<SysTagMapper, SysTag> implements SysTagService {

    @Autowired
    private SysUserTagService sysUserTagService;
    /**
     * 获取用户第一次登录时选择的标签集合
     * @return
     */
    @Override
    public Result<List<SysTag>> getFirstTag() {
        LoginUser currentUser = SecurityUtils.getCurrentUser();
        Long userId = currentUser.getUserId();
        List<Long> tagList = sysUserTagService.lambdaQuery()
                .eq(SysUserTag::getUserId, userId)
                .list().stream().map(SysUserTag::getTagId)
                .collect(Collectors.toList());
        if (tagList.isEmpty()) {
            return Result.failed( "用户没有选择标签");
        }
        // 查询标签详情
        List<SysTag> sysTags = this.listByIds(tagList);
        return Result.success(sysTags);

    }

    /**
     * 保存用户第一次登录时选择的标签集合
     */
    @Override
    public void saveFirstTag(List<Long> tagIds) {
        LoginUser currentUser = SecurityUtils.getCurrentUser();
        Long userId = currentUser.getUserId();

        // 检查是否已经选择过
        boolean exists = sysUserTagService.lambdaQuery()
                .eq(SysUserTag::getUserId, userId)
                .exists();
        if (exists) {
           throw new BizException("该用户已经选择过标签");
        }

        // 保存用户选择的标签
        List<SysUserTag> tags = tagIds.stream().map(tagId -> {
            SysUserTag tag = new SysUserTag();
            tag.setUserId(userId);
            tag.setTagId(tagId);
            return tag;
        }).toList();

        sysUserTagService.saveBatch(tags);

    }
}